package java114.jdbc;

import java.sql.*;
import java.text.MessageFormat;

public class Demo01_DriverManager {
    public static void main(String[] args) throws SQLException {
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;

        try{
            //1 加载数据库厂商提供的驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.获取数据库的连接
            connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/java114?characterEncoding=utf8" +
                            "&allowPublicKeyRetrieval=true&useSSL=false",
                    "root",
                    "123456");
            //3.创建Statment连接对象
            statement = connection.createStatement();
            //4  写SQL语句
            String sql = "select id, name, sno, age, gender, enroll_date, class_id from student";
            //5  执行SQL语句  接受返回结果
            resultSet = statement.executeQuery(sql);
            //6处理返回结果
            while(resultSet.next()){
                Long id = resultSet.getLong("id");
                String name = resultSet.getString("name");
                String sno = resultSet.getString("sno");
                int age = resultSet.getInt("age");
                Long gender = resultSet.getLong("gender");
                Date enrollDate = resultSet.getDate("enroll_date");
                Long classId = resultSet.getLong("class_id");
                System.out.println(MessageFormat.format("id={0}, name={1}, sno={2}, age={3}, gender={4}, enroll_date={5}, class_id={6}",
                                id, name, sno, age, gender, enrollDate, classId));
            }

        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally{
            //7关闭连接
            if(resultSet != null){
                try{
                    resultSet.close();
                }catch(SQLException e){
                    e.printStackTrace();
                }
            }

            if(statement != null){
                try{
                    statement.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if(connection != null){
                try{
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }

    }
}
